<template>
  <div id="search">
    <el-form class="form-flex" label-width="auto">
      <el-form-item label="送水时间">
        <el-col :span="11">
          <el-date-picker
            v-model="listQuery.startTime"
            type="date"
            aria-label="Pick a startTime"
            placeholder="Pick a startTime"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-col>
        <el-col class="text-center" :span="1" style="margin: 0 0.5rem"
          >-</el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="listQuery.endTime"
            aria-label="Pick an endTime"
            placeholder="Pick an endTime"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search"> 查询 </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" id="addButton" @click="openDialog"
      >添加</el-button
    >
  </div>
  <div id="list">
    <el-table :data="history" stripe style="width: 100%">
      <el-table-column prop="id" label="编号" />
      <el-table-column prop="custName" label="用户姓名" />
      <el-table-column prop="workerName" label="送水工姓名" />
      <el-table-column prop="sendWaterTime" label="送水时间" />
      <el-table-column prop="sendWaterCount" label="送水数量" />
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 为修改按钮绑定一个单击事件  scope表示槽位 row槽位的一行 -->
          <el-button type="primary" @click="preUpdate(scope.row)"
            >修改</el-button
          >
          <!--  为删除按钮绑定一个单击事件-->
          <el-button type="danger" @click="confirmDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 底部分页导航 -->
  <el-pagination
    v-model:current-page="listQuery.pageNum"
    v-model:page-size="listQuery.pageSize"
    :page-sizes="[2, 3, 5, 10]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <!--添加对话框-->
  <div id="myDialog">
    <!-- 
            dialogFormVisible 对话框是否可见
            @close="cleanForm" 对话框关闭执行的回调函数
            -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      width="500"
      @close="resetForm"
    >
      <el-form :model="dialogForm">
        <el-form-item label="用户姓名" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.custName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="送水工姓名" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.workerName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="送水时间" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.sendWaterTime" autocomplete="off" />
        </el-form-item>
        <el-form-item label="送水数量" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.sendWaterCount" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      history: [],
      listQuery: {
        pageNum: 1,
        pageSize: 5,
        startTime: null,
        endTime: null,
      },
      total: 0,
      // 对话框是否课件 true可见 false不可见，默认false
      dialogFormVisible: false,
      // 对话框表单
      dialogForm: {
        id: "",
        custName: "",
        workerName: "",
        sendWaterTime: "",
        sendWaterCount: "",
      },
      // 表单标签宽度
      formLabelWidth: "100px",
      // 对话框标签
      dialogTitle: "",
    };
  },
  computed: {
    ...mapState(['user'])
  },
  created() {
    // console.info("User is:",this.user)
    this.getHistory();
  },
  methods: {
    getHistory() {

      this.$axios
        .get("http://localhost:8091/history/list0", {
          params: this.listQuery,
          // 封装分页参数给后端
          // 封装开始时间和结束时间
        })
        // 请求成功后调用
        .then((res) => {
          console.log("listQuery = ", this.listQuery);
          // console.log(res);
          let code = res.data.code;
          if (code === 200) {
            this.history = res.data.data.list;
            this.total = res.data.data.total;
          }
        })
        // 请求失败后调用
        .catch((err) => {
          console.info(`请求失败${err}`);
          this.$message.error(`请求失败${err}`);
        });
    },
    handleSizeChange(val) {
      // 设置新的每页条数
      this.pageSize = val;
      // 当前页码默认是第一页
      this.pageNum = 1;
      // 重新进行分页查询
      this.getHistory();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getHistory();
    },
    saveHistory() {
      this.$axios
        .post("http://localhost:8091/history/add", this.dialogForm)
        .then((res) => {
          // console.info(res);
          let code = res.data.code;
          if (code === 200) {
            this.getHistory();
            this.$message.success("添加成功！");
          } else {
            this.$message.error("添加失败！");
          }
          // 清空对话框
          this.resetForm();
          // 关闭对话框
          this.dialogFormVisible = false;
        })
        .catch((err) => {
          (err) => {
            console.log("添加请求发送失败", err);
            this.$message.error("添加请求发送失败", err);
          };
        });
    },
    preUpdate(history) {
      this.dialogFormVisible = true;
      this.dialogTitle = "修改送水历史";
      // 将表格的信息更新到对话框的表单中
      this.$nextTick(() => {
        this.dialogForm = history;
      });
    },
    updateHistory() {
      this.$axios
        .put("http://localhost:8091/history/update", this.dialogForm)
        .then((res) => {
          let code = res.data.code;
          if (code === 200) {
            this.getHistory();
            this.$message.success("修改成功！");
          } else {
            this.$message.error("修改失败！");
          }
          // 清空对话框
          this.resetForm();
          // 关闭对话框
          this.dialogFormVisible = false;
        })
        .catch((err) => {
          (err) => {
            console.log("修改请求发送失败", err);
            this.$message.error("修改请求发送失败", err);
          };
        });
    },
    confirmDelete(id) {
      this.$confirm("确认要删除吗", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.removeById(id);
        })
        .catch((err) => {
          this.$message({
            type: "info",
            message: "操作已取消",
          });
        });
    },
    removeById(id) {
      this.$axios.delete("http://localhost:8091/history/delete/"+id)
      .then(res => {
        let code = res.data.code;
        if (code === 200) {
            this.getHistory();
            this.$message.success("删除成功！");
          } else {
            this.$message.error("删除成功！");
          }
      })
      .catch(err => {
        console.log("删除请求发送失败", err);
        this.$message.error("删除请求发送失败", err);
      })
    },
    search() {
      console.info(`开始时间是${this.listQuery.startTime}`);
      console.info(`结束时间是${this.listQuery.endTime}`);
      this.getHistory();
    },
    reset() {
      this.listQuery.startTime = null;
      this.listQuery.endTime = null;
      this.getHistory();
    },
    /**
     * 添加按钮click事件对应的处理函数，显示对话框，修改对话框标题
     */
    openDialog() {
      this.dialogFormVisible = true;
      this.dialogTitle = "添加送水历史";
    },
    resetForm() {
      this.dialogForm = {};
    },
    submit() {
      if (this.dialogTitle === "添加送水历史") {
        this.saveHistory();
      } else {
        this.updateHistory();
      }
    },
  },
};
</script>

<style scoped>
#search {
  display: flex;
  justify-content: space-between; /* 在主轴（默认水平方向）上分配空间 */
  align-items: center;
}

#search .form-flex {
  display: flex;
  flex: 1; /* 让表单占据剩余的空间 */
  justify-content: center;
  align-items: center;
}

#search #addButton {
  margin-left: auto;
}
</style>